/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.cms.guestbook.web;

import com.google.common.collect.Lists;
import com.jeeplus.cms.util.CaptchaUtils;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.cms.guestbook.entity.CmsGuestbook;
import com.jeeplus.modules.cms.guestbook.service.CmsGuestbookService;
import com.jeeplus.modules.cms.guestbook.vo.CaptchaVo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 留言表Controller
 * @author Sawyer
 * @version 2020-11-22
 */
@RestController
@RequestMapping(value = "/cms/guestbook/cmsGuestbook")
public class CmsGuestbookController extends BaseController {

	@Autowired
	private CmsGuestbookService cmsGuestbookService;

	@ModelAttribute
	public CmsGuestbook get(@RequestParam(required=false) String id) {
		CmsGuestbook entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = cmsGuestbookService.get(id);
		}
		if (entity == null){
			entity = new CmsGuestbook();
		}
		return entity;
	}

	/**
	 * 留言表列表数据
	 */
	@RequiresPermissions("cms:guestbook:cmsGuestbook:list")
	@GetMapping("list")
	public AjaxJson list(CmsGuestbook cmsGuestbook, HttpServletRequest request, HttpServletResponse response) {
		Page<CmsGuestbook> page = cmsGuestbookService.findPage(new Page<CmsGuestbook>(request, response), cmsGuestbook);
		return AjaxJson.success().put("page",page);
	}

	/**
	 * 根据Id获取留言表数据
	 */
	@RequiresPermissions(value={"cms:guestbook:cmsGuestbook:view","cms:guestbook:cmsGuestbook:add","cms:guestbook:cmsGuestbook:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(CmsGuestbook cmsGuestbook) {
		return AjaxJson.success().put("cmsGuestbook", cmsGuestbook);
	}

	/**
	 * 保存留言表
	 */
	@RequiresPermissions(value={"cms:guestbook:cmsGuestbook:add","cms:guestbook:cmsGuestbook:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(CmsGuestbook cmsGuestbook, CaptchaVo captchaVo, Model model) throws Exception{
		if (!CaptchaUtils.validateCaptcha(captchaVo)) {
			return AjaxJson.error("验证码错误");
		}
		String errMsg = beanValidator(cmsGuestbook);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑表单保存
		cmsGuestbookService.save(cmsGuestbook);
		return AjaxJson.success("保存留言表成功");
	}


	/**
	 * 批量删除留言表
	 */
	@RequiresPermissions("cms:guestbook:cmsGuestbook:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		if (jeePlusProperites.isDemoMode()) {
			return AjaxJson.error("演示模式，不允许操作！");
		}
		String[] idArray =ids.split(",");
		for(String id : idArray){
			cmsGuestbookService.delete(new CmsGuestbook(id));
		}
		return AjaxJson.success("删除留言表成功");
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("cms:guestbook:cmsGuestbook:export")
    @GetMapping("export")
    public AjaxJson exportFile(CmsGuestbook cmsGuestbook, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "留言表"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<CmsGuestbook> page = cmsGuestbookService.findPage(new Page<CmsGuestbook>(request, response, -1), cmsGuestbook);
    		new ExportExcel("留言表", CmsGuestbook.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出留言表记录失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("cms:guestbook:cmsGuestbook:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<CmsGuestbook> list = ei.getDataList(CmsGuestbook.class);
			for (CmsGuestbook cmsGuestbook : list){
				try{
					cmsGuestbookService.save(cmsGuestbook);
					successNum++;
				} catch(Exception ex){
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条留言表记录。");
			}

			return AjaxJson.success( "已成功导入 "+successNum+" 条留言表记录"+failureMsg);
		} catch (Exception e) {
			return AjaxJson.error("导入留言表失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 下载导入留言表数据模板
	 */
	@RequiresPermissions("cms:guestbook:cmsGuestbook:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "留言表数据导入模板.xlsx";
    		List<CmsGuestbook> list = Lists.newArrayList();
    		new ExportExcel("留言表数据", CmsGuestbook.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }


}
